<template>
  <div class="erp-account-config">
    <el-card shadow="never">
      <template #header>
        <div class="erp-account-config__header">
          <span>科目配置</span>
          <div>
            <el-button type="primary" size="small" @click="openCreate">新增</el-button>
            <el-button size="small" type="danger" :disabled="selectedRows.length === 0" @click="onBatchDelete">批量删除</el-button>
          </div>
        </div>
      </template>
      <el-form :inline="true" class="erp-account-config__search" @submit.prevent>
        <el-form-item label="单据类型">
          <el-select v-model="query.billType" placeholder="全部" clearable>
            <el-option value="PO_IN" label="采购入库" />
            <el-option value="SO_OUT" label="销售出库" />
          </el-select>
        </el-form-item>
        <el-form-item label="分录类型">
          <el-select v-model="query.entryType" placeholder="全部" clearable>
            <el-option value="STOCK" label="库存" />
            <el-option value="PAYABLE" label="应付" />
            <el-option value="RECEIVABLE" label="应收" />
            <el-option value="REVENUE" label="收入" />
            <el-option value="COST" label="成本" />
            <el-option value="TAX_IN" label="进项税" />
            <el-option value="TAX_OUT" label="销项税" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSearch">查询</el-button>
          <el-button size="small" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" size="small" style="width: 100%" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="48" />
        <el-table-column prop="billType" label="单据类型" min-width="120">
          <template #default="{ row }">
            <el-tag v-if="row.billType === 'PO_IN'" type="primary">采购入库</el-tag>
            <el-tag v-else-if="row.billType === 'SO_OUT'" type="success">销售出库</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="entryType" label="分录类型" min-width="120">
          <template #default="{ row }">
            {{ getEntryTypeLabel(row.entryType) }}
          </template>
        </el-table-column>
        <el-table-column prop="accountId" label="科目ID" min-width="120" />
        <el-table-column prop="dcFlag" label="借贷方向" min-width="100">
          <template #default="{ row }">
            <el-tag v-if="row.dcFlag === 'DEBIT'" type="success">借方</el-tag>
            <el-tag v-else-if="row.dcFlag === 'CREDIT'" type="warning">贷方</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" min-width="80" />
        <el-table-column prop="status" label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">{{ row.status === 1 ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="160" />
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openEdit(row)">编辑</el-button>
            <el-popconfirm title="确认删除该配置？" @confirm="onDelete(row)">
              <template #reference>
                <el-button link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="erp-account-config__pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="pageNum"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

    <!-- 编辑抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="单据类型" prop="billType">
          <el-select v-model="form.billType" placeholder="请选择单据类型" style="width: 100%">
            <el-option value="PO_IN" label="采购入库" />
            <el-option value="SO_OUT" label="销售出库" />
          </el-select>
        </el-form-item>
        <el-form-item label="分录类型" prop="entryType">
          <el-select v-model="form.entryType" placeholder="请选择分录类型" style="width: 100%">
            <el-option value="STOCK" label="库存" />
            <el-option value="PAYABLE" label="应付" />
            <el-option value="RECEIVABLE" label="应收" />
            <el-option value="REVENUE" label="收入" />
            <el-option value="COST" label="成本" />
            <el-option value="TAX_IN" label="进项税" />
            <el-option value="TAX_OUT" label="销项税" />
          </el-select>
        </el-form-item>
        <el-form-item label="科目ID" prop="accountId">
          <el-input v-model="form.accountId" placeholder="请输入科目ID" />
        </el-form-item>
        <el-form-item label="借贷方向" prop="dcFlag">
          <el-select v-model="form.dcFlag" placeholder="请选择借贷方向" style="width: 100%">
            <el-option value="DEBIT" label="借方" />
            <el-option value="CREDIT" label="贷方" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="form.priority" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item>
          <div style="text-align: center; width: 100%;">
            <el-button type="primary" :loading="submitLoading" @click="onSubmit">保存</el-button>
            <el-button @click="drawerVisible = false">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { pageAccountConfig, getAccountConfig, createAccountConfig, updateAccountConfig, deleteAccountConfig, type AccountConfigDTO } from '@/api/erp/accountConfig'
import { ElMessage } from 'element-plus'

const list = ref<any[]>([])
const selectedRows = ref<any[]>([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const query = reactive<{ billType?: string; entryType?: string }>({
  billType: '',
  entryType: ''
})

const drawerVisible = ref(false)
const isEdit = ref(false)
const drawerTitle = ref('新增配置')
const formRef = ref<FormInstance>()
const form = reactive<AccountConfigDTO>({
  billType: '',
  entryType: '',
  accountId: '',
  dcFlag: '',
  priority: 1,
  status: 1,
  remark: ''
})
const rules: FormRules = {
  billType: [{ required: true, message: '请选择单据类型', trigger: 'change' }],
  entryType: [{ required: true, message: '请选择分录类型', trigger: 'change' }],
  accountId: [{ required: true, message: '请输入科目ID', trigger: 'blur' }],
  dcFlag: [{ required: true, message: '请选择借贷方向', trigger: 'change' }]
}
const submitLoading = ref(false)

const getEntryTypeLabel = (type: string) => {
  const map: Record<string, string> = {
    STOCK: '库存',
    PAYABLE: '应付',
    RECEIVABLE: '应收',
    REVENUE: '收入',
    COST: '成本',
    TAX_IN: '进项税',
    TAX_OUT: '销项税'
  }
  return map[type] || type
}

const load = async () => {
  const res = await pageAccountConfig({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    billType: query.billType || undefined,
    entryType: query.entryType || undefined
  })
  list.value = res?.data?.records || []
  total.value = res?.data?.total || 0
}

const onPageChange = (p: number) => {
  pageNum.value = p
  load()
}
const onSizeChange = (s: number) => {
  pageSize.value = s
  pageNum.value = 1
  load()
}

const onSearch = () => {
  pageNum.value = 1
  load()
}

const onReset = () => {
  query.billType = ''
  query.entryType = ''
  onSearch()
}

const onSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

const openCreate = () => {
  isEdit.value = false
  drawerTitle.value = '新增配置'
  resetForm()
  drawerVisible.value = true
}

const openEdit = async (row: any) => {
  isEdit.value = true
  drawerTitle.value = '编辑配置'
  const res = await getAccountConfig(String(row.configId))
  Object.assign(form, {
    configId: String(res?.data?.configId),
    billType: res?.data?.billType || '',
    entryType: res?.data?.entryType || '',
    accountId: res?.data?.accountId ? String(res?.data?.accountId) : '',
    dcFlag: res?.data?.dcFlag || '',
    priority: res?.data?.priority || 1,
    status: res?.data?.status ?? 1,
    remark: res?.data?.remark || ''
  })
  drawerVisible.value = true
}

const resetForm = () => {
  form.configId = undefined
  form.billType = ''
  form.entryType = ''
  form.accountId = ''
  form.dcFlag = ''
  form.priority = 1
  form.status = 1
  form.remark = ''
  formRef.value?.clearValidate()
}

const onSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (isEdit.value && form.configId) {
          await updateAccountConfig(form.configId, form)
          ElMessage.success('更新成功')
        } else {
          await createAccountConfig(form)
          ElMessage.success('新增成功')
        }
        drawerVisible.value = false
        load()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const onDelete = async (row: any) => {
  try {
    await deleteAccountConfig(String(row.configId))
    ElMessage.success('删除成功')
    load()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const onBatchDelete = async () => {
  if (selectedRows.value.length === 0) return
  try {
    await Promise.all(selectedRows.value.map(row => deleteAccountConfig(String(row.configId))))
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    load()
  } catch (error) {
    ElMessage.error('批量删除失败')
  }
}

onMounted(load)
</script>

<style scoped lang="scss">
.erp-account-config {
  &__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  &__pagination {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

